package com.example.aigc_education.security.config;

import com.example.aigc_education.security.filter.MobileAuthenticationFilter;
import com.example.aigc_education.security.filter.MobileCodeValidateFilter;
import com.example.aigc_education.security.filter.WeChatAuthenticationFilter;
import com.example.aigc_education.security.handle.CustomAuthenticationFailureHandler;
import com.example.aigc_education.security.handle.CustomAuthenticationSuccessHandler;
import com.example.aigc_education.security.provider.MobileAuthenticationProvider;
import com.example.aigc_education.security.provider.WeChatAuthenticationProvider;
import com.example.aigc_education.security.service.WeChatUserDetailsServiceImpl;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 微信登录配置
 */
@Component
public class WeChatAuthenticationConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {


    @Resource
    private CustomAuthenticationFailureHandler authenticationFailureHandler;

    @Resource
    private CustomAuthenticationSuccessHandler authenticationSuccessHandler;

    @Resource
    private WeChatUserDetailsServiceImpl userDetailsService;



    @Override
    public void configure(HttpSecurity http) throws Exception {
        WeChatAuthenticationFilter filter = new WeChatAuthenticationFilter();

        AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
        filter.setAuthenticationManager(authenticationManager);

        filter.setAuthenticationFailureHandler(authenticationFailureHandler);
        filter.setAuthenticationSuccessHandler(authenticationSuccessHandler);

        SessionAuthenticationStrategy sessionAuthenticationStrategy = http.getSharedObject(SessionAuthenticationStrategy.class);
        filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy);

        http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);

        WeChatAuthenticationProvider provider = new WeChatAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);

        http.authenticationProvider(provider);
    }
}

